<template>
	<view class="application-list-container">
		<!-- 筛选器 -->
		<view class="filter-section">
			<view class="filter-tabs">
				<view 
					v-for="(filter, key) in statusFilters" 
					:key="key"
					class="filter-tab"
					:class="{ active: activeStatusFilter === key }"
					@click="changeStatusFilter(key)"
				>
					<text class="filter-tab-text">{{ filter.label }}</text>
					<text class="filter-count">({{ getFilterCount(key) }})</text>
				</view>
			</view>
		</view>
		
		<!-- 比赛申请列表 -->
		<view class="application-list">
			<view v-if="applicationList.length === 0" class="empty-state">
				<text class="empty-icon">📋</text>
				<text class="empty-text">暂无申请记录</text>
			</view>
			
			<!-- 按系列赛分组显示 -->
			<view v-for="(series, seriesIndex) in filteredGroupedApplications" :key="series.series_name" class="series-group">
				<!-- 系列赛标题 -->
				<view class="series-header">
					<text class="series-title">{{ series.series_name }}</text>
					<text class="series-count">({{ series.matches.length }}场比赛)</text>
				</view>
				
				<!-- 该系列赛下的具体比赛 -->
				<view v-for="(match, matchIndex) in series.matches" :key="match.match_key" class="match-item">
					<view class="match-card">
						<!-- 具体比赛信息 -->
						<view class="match-header">
							<view class="match-details">
								<view class="detail-row">
									<text class="detail-icon">📅</text>
									<text class="detail-text">{{ formatMatchDate(match.match_date) }}</text>
								</view>
								<view class="detail-row">
									<text class="detail-icon">⏰</text>
									<text class="detail-text">{{ match.match_time_slot || '时段未定' }}</text>
								</view>
								<view class="detail-row">
									<text class="detail-icon">⚽</text>
									<text class="detail-text">{{ match.match_teams || '对阵待定' }}</text>
								</view>
								<view class="detail-row">
									<text class="detail-icon">🏟️</text>
									<text class="detail-text">{{ match.match_field || '场地待定' }}</text>
								</view>
							</view>
						</view>
						
						<!-- 申请岗位列表 -->
						<view class="positions-section">
							<view class="positions-title">申请岗位</view>
							<view class="positions-list">
								<view v-for="app in match.applications" :key="app._id" class="position-item">
									<view class="position-info">
										<text class="position-name">{{ getPositionName(app.applied_position) }}</text>
										<view class="position-status" :class="'status-' + app.status">
											<text class="status-text">{{ getApplicationStatusText(app.status) }}</text>
											<text v-if="app.status === 'confirmed'" class="selected-mark">🎯</text>
										</view>
									</view>
									<view class="apply-time">
										<text class="time-text">{{ formatDateTime(app.apply_time) }}</text>
									</view>
								</view>
							</view>
							
							<!-- 意向岗位信息 -->
							<view v-if="getMatchPreferredPositions(match).length > 0" class="preferred-positions-section">
								<view class="preferred-positions-info">
									<text class="preferred-icon">🎯</text>
									<text class="preferred-text">意向岗位：{{ getMatchPreferredPositions(match).join('、') }}</text>
								</view>
							</view>
						</view>
						
						<!-- 操作按钮区域 -->
						<view class="application-actions">
							<!-- 查看选派表按钮 - 只有已选派状态才显示 -->
							<button v-if="hasConfirmedPosition(match)" 
									class="schedule-btn" 
									@click="viewSchedule(match)" 
									:disabled="loading">
								<text class="btn-text">查看选派表</text>
							</button>
							
							<!-- 取消申请按钮 -->
							<button class="cancel-btn" 
									@click="cancelApplications(match)"
									:disabled="loading">
								<text class="btn-text">{{ getCancelButtonText(match) }}</text>
							</button>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			applicationList: [],
			reviewing: false,
			loading: false,
			
			// 筛选状态
			activeStatusFilter: 'all',
			statusFilters: {
				all: { label: '全部' },
				pending: { label: '待审核' },
				selected: { label: '已确定' },
				confirmed: { label: '已选派' },
				rejected: { label: '未通过' }
			},
			
			// 岗位名称映射
			positionNames: {
				main_referee: '主裁判',
				assistant_referee: '助理裁判',
				fourth_official: '第四官员',
				referee_supervisor: '裁判监督',
				'主裁判': '主裁判',
				'助理裁判': '助理裁判',
				'第四官员': '第四官员',
				'裁判监督': '裁判监督'
			}
		}
	},
	
	computed: {
		// 按系列赛和具体比赛分组的申请列表
		groupedApplications() {
			const seriesGroups = {}
			
			this.applicationList.forEach(app => {
				// 获取系列赛名称（比赛的主标题）
				const seriesName = app.match_name || '未知系列赛'
				
				// 创建具体比赛的唯一标识（日期+时间+对阵）
				const matchKey = `${app.match_date || 'unknown'}_${app.match_time_slot || 'unknown'}_${app.match_teams || 'unknown'}`
				
				if (!seriesGroups[seriesName]) {
					seriesGroups[seriesName] = {
						series_name: seriesName,
						matches: {}
					}
				}
				
				if (!seriesGroups[seriesName].matches[matchKey]) {
					seriesGroups[seriesName].matches[matchKey] = {
						match_key: matchKey,
						match_date: app.match_date,
						match_time_slot: app.match_time_slot,
						match_teams: app.match_teams,
						match_field: app.match_field,
						schedule_id: app.schedule_id,
						session_id: app.session_id,
						applications: []
					}
				}
				
				seriesGroups[seriesName].matches[matchKey].applications.push(app)
			})
			
			// 转换为数组格式并排序
			return Object.values(seriesGroups).map(series => ({
				...series,
				matches: Object.values(series.matches).sort((a, b) => {
					// 按日期和时间排序
					const dateA = new Date(a.match_date || '1970-01-01')
					const dateB = new Date(b.match_date || '1970-01-01')
					return dateA - dateB
				})
			})).sort((a, b) => a.series_name.localeCompare(b.series_name))
		},
		
		// 过滤后的分组申请列表
		filteredGroupedApplications() {
			if (this.activeStatusFilter === 'all') {
				return this.groupedApplications
			}
			
			return this.groupedApplications.map(series => ({
				...series,
				matches: series.matches.map(match => ({
					...match,
					applications: match.applications.filter(app => app.status === this.activeStatusFilter)
				})).filter(match => match.applications.length > 0)
			})).filter(series => series.matches.length > 0)
		}
	},
	
	onLoad(options) {
		this.loadApplicationList()
	},
	
	methods: {
		// 加载申请列表
		async loadApplicationList() {
			try {
				// 获取用户信息
				const userInfoStr = uni.getStorageSync('userInfo')
				if (!userInfoStr) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				
				const userInfo = JSON.parse(userInfoStr)
				const userId = userInfo._id || userInfo.userId || userInfo.id
				
				console.log('加载用户的所有申请记录，用户ID:', userId)
				
				const matchObject = uniCloud.importObject('match-object')
				const result = await matchObject.getMyApplications()
				
				if (result.code === 0) {
					this.applicationList = result.data || []
					console.log('加载的申请记录数量:', this.applicationList.length)
					console.log('申请记录详情:', this.applicationList)
				} else {
					console.error('获取我的申请失败:', result.message)
					uni.showToast({
						title: result.message || '获取数据失败',
						icon: 'none'
					})
					this.applicationList = []
				}
				
			} catch (error) {
				console.error('加载申请列表失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
				this.applicationList = []
			}
		},
		
		// 切换状态筛选
		changeStatusFilter(filterKey) {
			this.activeStatusFilter = filterKey
		},
		
		// 获取筛选数量
		getFilterCount(filterKey) {
			if (!this.applicationList || !Array.isArray(this.applicationList)) {
				return 0
			}
			if (filterKey === 'all') {
				// 计算总的比赛场次数
				return this.groupedApplications.reduce((total, series) => total + series.matches.length, 0)
			}
			// 计算包含特定状态申请的比赛场次数
			return this.groupedApplications.reduce((total, series) => {
				const matchesWithStatus = series.matches.filter(match => 
					match.applications.some(app => app.status === filterKey)
				)
				return total + matchesWithStatus.length
			}, 0)
		},
		
		// 格式化比赛日期
		formatMatchDate(date) {
			if (!date) return '日期待定'
			
			// 如果是日期字符串格式 "2024-01-15"
			if (typeof date === 'string' && date.includes('-')) {
				const parts = date.split('-')
				if (parts.length === 3) {
					const month = parts[1]
					const day = parts[2]
					const dateObj = new Date(date)
					const weekdays = ['日', '一', '二', '三', '四', '五', '六']
					const weekday = weekdays[dateObj.getDay()]
					return `${month}月${day}日 星期${weekday}`
				}
			}
			
			// 如果是时间戳或Date对象
			const d = new Date(date)
			if (isNaN(d.getTime())) return '日期待定'
			
			const month = String(d.getMonth() + 1).padStart(2, '0')
			const day = String(d.getDate()).padStart(2, '0')
			const weekdays = ['日', '一', '二', '三', '四', '五', '六']
			const weekday = weekdays[d.getDay()]
			return `${month}月${day}日 星期${weekday}`
		},
		
		// 格式化日期时间
		formatDateTime(date) {
			if (!date) return ''
			const d = new Date(date)
			if (isNaN(d.getTime())) return ''
			
			const month = String(d.getMonth() + 1).padStart(2, '0')
			const day = String(d.getDate()).padStart(2, '0')
			const hour = String(d.getHours()).padStart(2, '0')
			const minute = String(d.getMinutes()).padStart(2, '0')
			return `${month}-${day} ${hour}:${minute}`
		},
		
		// 获取岗位名称
		getPositionName(position) {
			return this.positionNames[position] || position || '未知岗位'
		},
		
		// 获取比赛的意向岗位信息
		getMatchPreferredPositions(match) {
			if (!match.applications || match.applications.length === 0) {
				return []
			}
			
			// 获取第一个申请的意向岗位信息（因为是自动报名，所有申请的意向岗位应该是一样的）
			const firstApplication = match.applications[0]
			if (!firstApplication.preferred_positions || firstApplication.preferred_positions.length === 0) {
				return []
			}
			
			// 将意向岗位key转换为显示名称
			return firstApplication.preferred_positions.map(key => 
				this.positionNames[key] || key
			)
		},
		
		// 获取申请状态文本
		getApplicationStatusText(status) {
			const statusMap = {
				'pending': '待审核',
				'selected': '已确定',
				'confirmed': '已选派',
				'rejected': '未通过',
				'cancelled': '已取消'
			}
			return statusMap[status] || status
		},
		
		// 判断是否有已确认的岗位
		hasConfirmedPosition(match) {
			return match.applications.some(app => app.status === 'confirmed' && app.has_schedule)
		},
		
		// 获取取消按钮文本
		getCancelButtonText(match) {
			const pendingApps = match.applications.filter(app => app.status === 'pending')
			const selectedApps = match.applications.filter(app => app.status === 'selected')
			const confirmedApps = match.applications.filter(app => app.status === 'confirmed')
			
			if (pendingApps.length > 0) {
				return '取消申请'
			} else if (selectedApps.length > 0 || confirmedApps.length > 0) {
				return '联系组织者'
			} else {
				return '已处理完毕'
			}
		},
		
		// 判断是否有可取消的申请
		hasCancellableApplications(match) {
			return match.applications.some(app => app.status === 'pending')
		},
		
		// 查看选派表
		async viewSchedule(match) {
			if (!match.session_id) {
				uni.showToast({
					title: '选派表信息不完整',
					icon: 'none'
				})
				return
			}
			
			this.loading = true
			try {
				// 获取用户信息
				const userInfoStr = uni.getStorageSync('userInfo')
				if (!userInfoStr) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				
				const userInfo = JSON.parse(userInfoStr)
				const userId = userInfo._id || userInfo.userId || userInfo.id
				
				// 调用云对象获取选派表数据
				const matchScheduleObject = uniCloud.importObject('match-schedule-object')
				const result = await matchScheduleObject.getRoundSelectionSummary({
					sessionIds: [match.session_id],
					viewerRole: 'referee',
					viewerId: userId
				})
				
				if (result.code === 0) {
					// 将数据存储到本地，避免URL过长
					const scheduleKey = `schedule_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
					uni.setStorageSync(scheduleKey, result.data)
					
					// 跳转到选派表查看页面，传递存储key
					uni.navigateTo({
						url: `/packageMy/my/schedule-viewer?key=${scheduleKey}&role=referee&highlightUser=${userId}`
					})
				} else {
					uni.showToast({
						title: result.message || '获取选派表失败',
						icon: 'none'
					})
				}
				
			} catch (error) {
				console.error('查看选派表失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		
		// 取消申请
		async cancelApplications(match) {
			try {
				const pendingApps = match.applications.filter(app => app.status === 'pending')
				const selectedApps = match.applications.filter(app => app.status === 'selected')
				const confirmedApps = match.applications.filter(app => app.status === 'confirmed')
				
				// 根据申请状态显示不同的确认提示
				let confirmResult;
				let actionType = '';
				
				if (pendingApps.length > 0) {
					// 有待审核的申请，可以直接取消
					const positionNames = pendingApps.map(app => this.getPositionName(app.applied_position)).join('、')
					confirmResult = await uni.showModal({
						title: '确认取消',
						content: `确定要取消以下岗位的申请吗？\n\n${positionNames}`,
						confirmText: '确认取消',
						cancelText: '保留申请',
						confirmColor: '#ff4d4f'
					})
					actionType = 'cancel'
				} else if (selectedApps.length > 0 || confirmedApps.length > 0) {
					// 已确定或已选派的申请，需要联系组织者
					const allPositions = [...selectedApps, ...confirmedApps]
					const positionNames = allPositions.map(app => this.getPositionName(app.applied_position)).join('、')
					const statusInfo = allPositions.map(app => 
						`${this.getPositionName(app.applied_position)}(${this.getApplicationStatusText(app.status)})`
					).join('、')
					
					confirmResult = await uni.showModal({
						title: '⚠️ 重要提醒',
						content: `以下岗位申请已被处理，需要联系比赛组织者：\n\n${statusInfo}\n\n其中"已选派"状态表示已完成最终选派，通常不允许取消。`,
						confirmText: '联系组织者',
						cancelText: '稍后处理',
						confirmColor: '#ff4d4f'
					})
					actionType = 'contact'
				} else {
					uni.showToast({
						title: '所有申请已处理完毕',
						icon: 'none',
						duration: 2000
					})
					return
				}
				
				if (!confirmResult.confirm) return
				
				if (actionType === 'contact') {
					// 联系组织者的逻辑（可以跳转到联系页面或显示联系方式）
					uni.showModal({
						title: '联系方式',
						content: '请通过以下方式联系比赛组织者：\n\n电话：400-123-4567\n微信：比赛组织群\n邮箱：admin@match.com',
						showCancel: false,
						confirmText: '知道了'
					})
					return
				}
				
				// 执行取消操作
				uni.showLoading({ title: '正在取消...' })
				
				const matchScheduleObject = uniCloud.importObject('match-schedule-object')
				
				// 【修改】批量取消 - 只调用一次，后端会处理该时段的所有申请
				console.log('批量取消申请，使用第一个申请的信息:', pendingApps[0])
				const cancelResult = await matchScheduleObject.cancelSlotRefereeApplication({
					schedule_id: pendingApps[0].schedule_id,
					slot_id: pendingApps[0].slot_id,
					application_id: pendingApps[0].application_id  // 保持兼容性，但后端主要根据 slot_id 和 user_id 批量处理
				})
				
				console.log('批量取消结果:', cancelResult)
				
				if (cancelResult.code === 0) {
					const { cancelled_count, not_cancellable_count, not_cancellable_details } = cancelResult.data
					
					if (not_cancellable_count === 0) {
						// 全部取消成功
						uni.showToast({ 
							title: `成功取消${cancelled_count}个申请`, 
							icon: 'success',
							duration: 1500
						})
					} else {
						// 部分取消成功
						const failedInfo = not_cancellable_details.map(detail => 
							`${detail.position}: ${detail.reason}`
						).join('\n')
						
						uni.showModal({
							title: '部分取消成功',
							content: `成功取消${cancelled_count}个申请\n\n无法取消的申请：\n${failedInfo}`,
							showCancel: false,
							confirmText: '知道了'
						})
					}
					
					// 刷新申请列表
					setTimeout(() => {
						this.loadApplicationList()
					}, 1000)
					
				} else {
					// 取消失败
					uni.showModal({
						title: '取消失败',
						content: cancelResult.message || '取消申请失败，请重试',
						showCancel: false,
						confirmText: '知道了'
					})
				}
				
			} catch (error) {
				console.error('取消申请失败:', error)
				uni.showModal({
					title: '网络错误',
					content: '网络连接失败，请检查网络后重试',
					showCancel: false,
					confirmText: '知道了'
				})
			} finally {
				uni.hideLoading()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.application-list-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding: 20rpx;
}

// 申请列表
.application-list {
	.empty-state {
		text-align: center;
		padding: 120rpx 40rpx;
		
		.empty-icon {
			font-size: 120rpx;
			margin-bottom: 30rpx;
			display: block;
		}
		
		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}
}

// 系列赛分组
.series-group {
	margin-bottom: 40rpx;
}

.series-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: linear-gradient(135deg, #1BAE76, #52c41a);
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(27, 174, 118, 0.2);
	
	.series-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #fff;
	}
	
	.series-count {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.8);
		background-color: rgba(255, 255, 255, 0.2);
		padding: 6rpx 12rpx;
		border-radius: 20rpx;
	}
}

// 具体比赛项目
.match-item {
	margin-bottom: 20rpx;
}

.match-card {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	margin-left: 20rpx;
	border-left: 4rpx solid #1BAE76;
}

.match-header {
	margin-bottom: 20rpx;
	
	.match-details {
		.detail-row {
			display: flex;
			align-items: center;
			margin-bottom: 12rpx;
			
			&:last-child {
				margin-bottom: 0;
			}
			
			.detail-icon {
				font-size: 24rpx;
				margin-right: 12rpx;
				width: 32rpx;
			}
			
			.detail-text {
				font-size: 26rpx;
				color: #666;
				flex: 1;
			}
		}
	}
}



// 操作按钮区域
.application-actions {
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 1rpx solid #f0f0f0;
	display: flex;
	gap: 20rpx;
	
	.schedule-btn {
		flex: 1;
		height: 72rpx;
		background: linear-gradient(45deg, #1BAE76, #52c41a);
		border: none;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 8rpx rgba(27, 174, 118, 0.3);
		
		&:active {
			background: linear-gradient(45deg, #0f8c5c, #389e0d);
			transform: scale(0.98);
		}
		
		&:disabled {
			opacity: 0.6;
			transform: none;
		}
		
		.btn-text {
			color: #fff;
			font-size: 28rpx;
			font-weight: 500;
		}
	}
	
	.cancel-btn {
		flex: 1;
		height: 72rpx;
		background: linear-gradient(45deg, #ff7875, #ff4d4f);
		border: none;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.3);
		
		&:active {
			background: linear-gradient(45deg, #ff4d4f, #cf1322);
			transform: scale(0.98);
		}
		
		&:disabled {
			opacity: 0.6;
			transform: none;
		}
		
		.btn-text {
			color: #fff;
			font-size: 28rpx;
			font-weight: 500;
		}
	}
}

// 筛选区域
.filter-section {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 20rpx 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	margin-bottom: 20rpx;
}

.filter-tabs {
	display: flex;
	gap: 20rpx;
	
	.filter-tab {
		flex: 1;
		text-align: center;
		padding: 16rpx 20rpx;
		border-radius: 8rpx;
		background-color: #f5f5f5;
		
		&.active {
			background-color: #1BAE76;
			
			.filter-tab-text,
			.filter-count {
				color: #fff;
			}
		}
		
		.filter-tab-text {
			font-size: 26rpx;
			color: #666;
		}
		
		.filter-count {
			font-size: 22rpx;
			color: #999;
			margin-left: 8rpx;
		}
	}
}

// 申请岗位区域
.positions-section {
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 1rpx solid #f0f0f0;
	
	.positions-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 16rpx;
	}
	
	.positions-list {
		.position-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 16rpx 0;
			border-bottom: 1rpx solid #f8f8f8;
			
			&:last-child {
				border-bottom: none;
			}
			
			.position-info {
				display: flex;
				align-items: center;
				gap: 16rpx;
				flex: 1;
				
				.position-name {
					font-size: 26rpx;
					color: #333;
					font-weight: 500;
				}
				
				.position-status {
					display: flex;
					align-items: center;
					gap: 8rpx;
					padding: 6rpx 12rpx;
					border-radius: 16rpx;
					font-size: 20rpx;
					
					&.status-pending {
						background-color: #faad14;
						color: #fff;
					}
					
					&.status-selected {
						background-color: #722ed1;
						color: #fff;
					}
					
					&.status-confirmed {
						background: linear-gradient(45deg, #722ed1, #52c41a);
						color: #fff;
					}
					
					&.status-rejected {
						background-color: #ff4d4f;
						color: #fff;
					}
					
					&.status-cancelled {
						background-color: #d9d9d9;
						color: #666;
					}
					
					.status-text {
						font-size: 20rpx;
					}
					
					.selected-mark {
						font-size: 18rpx;
					}
				}
			}
			
			.apply-time {
				.time-text {
					font-size: 20rpx;
					color: #999;
				}
			}
		}
	}
	
	// 意向岗位信息样式
	.preferred-positions-section {
		margin-top: 16rpx;
		padding-top: 16rpx;
		border-top: 1rpx dashed #e8e8e8;
		
		.preferred-positions-info {
			display: flex;
			align-items: center;
			gap: 8rpx;
			padding: 12rpx 16rpx;
			background: rgba(67, 207, 124, 0.1);
			border-radius: 8rpx;
			border-left: 4rpx solid #43CF7C;
			
			.preferred-icon {
				font-size: 20rpx;
				line-height: 1;
				flex-shrink: 0;
			}
			
			.preferred-text {
				font-size: 22rpx;
				color: #43CF7C;
				line-height: 1.4;
				flex: 1;
				font-weight: 600;
			}
		}
	}
}
</style> 